let ws = null // new WebSocket(`ws://${document.location.origin}/v1/ws/`)

const state = {
  connected: false
}

export default {
  state,
  mutations: {
    connected: (state, status) => {
      state.connected = status
    }
  },
  actions: {
    init: ({
      commit
    }, _showNotice) => {
      if (ws == null) {
        var ws1 = new WebSocket(`ws://${document.location.origin.substring('http://'.length)}/v1/weixin/test1`, 'graphql-ws')
        //         {"type":"connection_init"}
        // {"type":"connection_ack"}
        // {"type":"start","id":"test_1","payload":{"query":"query fff\n {\n todos(input: {text: \"213\", userId: \"123\"}) {\n text\n }\n }\n "}}
        // {"payload":{"data":{"todos":[]}},"id":"test_1","type":"data"}
        // {"id":"test_1","type":"complete"}
        ws1.onopen = () => {
          ws1.send(JSON.stringify({
            type: 'connection_init'
          }))
        }
        ws1.onmessage = (msg) => {
          console.log(msg.data)
          const m = JSON.parse(msg.data)
          if (m.type === 'connection_ack') {
            ws1.send(JSON.stringify({
              type: 'start',
              id: 'test_1',
              payload: {
                query: `query fff
              {
               todos(input: {text: "213", userId: "123"}) {
                 text
               }
             }
             `
              }
            }))
          }
        }
        ws1.onerror = (err) => {
          console.log(err)
        }
        ws = new WebSocket(`ws://${document.location.origin.substring('http://'.length)}/v1/ws/?name=admin`)
        console.log(document.location.origin)
        ws.onopen = () => {
          commit('connected', true)
          if (_showNotice != null) {
            _showNotice('info', '已连接到服务器')
          }
        }
        ws.onclose = () => {
          ws = null
          commit('connected', false)
          if (_showNotice != null) {
            _showNotice('info', '已断开长连接')
          }
        }
        ws.onmessage = (evt) => {
          console.log(evt.data)
          if (_showNotice != null) {
            _showNotice('info', evt.data)
          }
        }
        ws.onerror = (evt) => {
          console.log(evt.data)
          if (_showNotice != null) {
            _showNotice('error', evt.data)
          }
        }
      }
    }
  }
}
